<!--
 * @Author: lp
 * @Date: 2022-03-09 16:22:33
 * @LastEditTime: 2022-05-13 15:56:22
 * @LastEditors: lp 654528967@qq.com
 * @Description: 自定义表格单元格
 * @FilePath: \nien-vue3-admin\src\components\customTable\cell.vue
-->
<script lang="ts">
import { defineComponent, h, computed, toRefs } from 'vue'
import useDicts, { DictDirection, dictInfo } from '@/store/modules/dicts'
import { praseStrEmpty } from '@/utils'

const dicts = useDicts()
export default defineComponent({
  props: {
    render: {
      type: Function,
      default: null,
    },
    row: {
      default: () => ({}),
      type: Object,
    },
    index: {
      default: null,
      type: Number,
    },
    autoFormatter: {
      default: () => ({}),
      type: Object,
    },
    formatter: {
      default: () => {},
      type: Function,
    },
  },
  setup(props) {
    const selfProps = props
    
    if (selfProps.render) {
      return () => selfProps.render(h, { row: selfProps.row, index: selfProps.index })
    }
    if (selfProps.autoFormatter) {
      if (selfProps.autoFormatter.dict in DictDirection) {
        // 这里先请求的原因是如果没设置dictLabel,dictValue,报错会导致请求发不出去
        dicts.setDicts(selfProps.autoFormatter.dict)
      }
      const dictItem = dictInfo[selfProps.autoFormatter.dict]
      const computedDictInfo:{
        dictValue:string,
        dictLabel:string
      } = {
        dictValue: '',
        dictLabel: '',
      }
      if (typeof dictItem.url === 'function') {
        const setDict = (feild, key) => {
          if (praseStrEmpty(feild) === '') {
            if (praseStrEmpty(dictItem[key]) === '') throw new Error(`${ DictDirection[selfProps.autoFormatter.dict] }字典未设置dictValue`)
            return dictItem[key]
          } 
          return feild
        }

        computedDictInfo.dictValue = setDict(selfProps.autoFormatter.dictValue, 'dictValue')

        computedDictInfo.dictLabel = setDict(selfProps.autoFormatter.dictLabel, 'dictLabel')
        if (!selfProps.autoFormatter.rowKey) throw new Error('rowKey未定义，该字典为非常规字典,rowKey表示要回显对应的真实值')
      } else {
        computedDictInfo.dictValue = 'dictValue'
        computedDictInfo.dictLabel = 'dictLabel'
      }
      // row 动态追踪响应式数据变化，更新dom
      const { row } = toRefs(props)
      if (Array.isArray(selfProps.autoFormatter.dict)) {
        return () => h('span', selfProps.formatter(selfProps.autoFormatter.dict, computedDictInfo.dictLabel, computedDictInfo.dictValue, selfProps.autoFormatter.rowKey, row && row.value))
      } 
      if (selfProps.autoFormatter.dict in DictDirection) {
        const dict = computed(() => dicts[selfProps.autoFormatter.dict])
        return () => h('span', selfProps.formatter(dict.value, computedDictInfo.dictLabel, computedDictInfo.dictValue, selfProps.autoFormatter.rowKey, row && row.value))
      } 
      return () => h('span', '字典未定义')
    }
  },
})
</script>
